import { type NextRequest, NextResponse } from "next/server"

function containsInappropriateContent(text: string): boolean {
  // 只检查最严重的暴力词汇，快速过滤
  const badWords = [
    'kill', 'murder', 'blood', 'violence', 'weapon', 'gun', 'knife', 'war',
    '杀死', '杀害', '谋杀', '血腥', '暴力', '武器', '刀', '枪', '战争'
  ]
  
  const lowerText = text.toLowerCase()
  return badWords.some(word => lowerText.includes(word))
}

function validateInput(data: any): { isValid: boolean; error?: string } {
  const { character, location, background, plotType } = data

  if (!character || !location || !background || !plotType) {
    return { isValid: false, error: "所有字段都是必填的 (All fields are required)" }
  }

  if (
    typeof character !== "string" ||
    typeof location !== "string" ||
    typeof background !== "string" ||
    typeof plotType !== "string"
  ) {
    return { isValid: false, error: "所有字段必须是字符串类型 (All fields must be strings)" }
  }

  if (character.length > 100 || location.length > 100 || background.length > 200 || plotType.length > 100) {
    return { isValid: false, error: "输入内容过长，请缩短后重试 (Input too long, please shorten)" }
  }

  // 内容安全检查
  const allInputs = `${character} ${location} ${background} ${plotType}`
  if (containsInappropriateContent(allInputs)) {
    return { isValid: false, error: "输入内容包含不当信息，请修改后重试 (Input contains inappropriate content)" }
  }

  return { isValid: true }
}

async function generateStory(
  character: string,
  location: string,
  background: string,
  plotType: string,
): Promise<string> {
  const systemPrompt = `Write a short children's story in English. Positive, simple, 100-150 words. Happy ending.

Character: ${character}
Location: ${location}
Background: ${background}
Plot: ${plotType}

Return only: Title + Story content.`

  const story = await callDeepSeekAPI(systemPrompt)

  // 简单关键词过滤（非AI检查）
  if (containsInappropriateContent(story)) {
    console.log("[v0] Story filtered due to inappropriate content")
    throw new Error("Generated story contains inappropriate content, please try again")
  }

  return story
}

async function callDeepSeekAPI(prompt: string): Promise<string> {
  const apiKey = process.env.DEEPSEEK_API_KEY

  if (!apiKey) {
    return "API key not found"
  }

  console.log("[v0] Calling Aizex API...")

  const response = await fetch("https://aizex.top/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      model: "deepseek-v3",
      messages: [
        {
          role: "system",
          content: "Write short children's stories in English. Positive, simple, 100-150 words.",
        },
        {
          role: "user",
          content: prompt,
        },
      ],
      max_tokens: 300,
      temperature: 0.9,
      stream: false,
    }),
  })

  const data = await response.json()
  console.log("[v0] Aizex API response received")

  return data.choices?.[0]?.message?.content?.trim() || "Story generation failed"
}


export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    // 验证输入
    const validation = validateInput(body)
    if (!validation.isValid) {
      return NextResponse.json({ error: validation.error }, { status: 400 })
    }

    const { character, location, background, plotType } = body

    // 生成故事
    const story = await generateStory(character, location, background, plotType)

    return NextResponse.json({
      story,
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error("故事生成错误:", error)

    return NextResponse.json({ error: "服务器内部错误，请稍后重试" }, { status: 500 })
  }
}

// 健康检查端点
export async function GET() {
  return NextResponse.json({
    status: "ok",
    service: "Children's Story Generation API",
    version: "1.0.0",
  })
}
